package com.haozhen

import akka.actor.{AbstractActor, Actor, ActorRef, ActorSystem, Props}

import scala.io.StdIn

/**
  * @author haozhen
  * @email haozh@ync1.com
  * @date 2020/12/8  23:24
  *
  *       4、Actor间通讯
  *       作业要求：
  *       1、编写 2 个 Actor ，分别是 AActor 和 BActor
  *       2、AActor 和 BActor 之间可以相互发送消息
  */

case class StartMessage(msg:String)

case class StopMessage(msg:String)

case class AMessage(msg:String)

case class BMessage(msg:String)


class AActor extends  Actor {

  var count = 0

  override def receive: Receive = {
    case BMessage(msg)=>{
      count+=1
      println("BActor"+msg)
      sender ! AMessage(s"(黄飞鸿):厉害，看我佛山无影脚...第 $count 脚")
    }
    case StartMessage(msg)=>{
      count+=1
      println("AActor"+msg)
      sender ! AMessage(s"(黄飞鸿):看我佛山无影脚...第 $count 脚")
    }
    case StopMessage(msg)=>{
      println(s"BActor乔峰：$msg")
      context.stop(self)
    }
  }

}

class BActor(a:ActorRef) extends Actor{

  var count = 0

  override def receive: Receive = {
    case AMessage(msg)=>{
      if(count>9){
        sender ! StopMessage("点到为止！！！")
        context.stop(self)
      }else{
        count+=1
        println("AActor"+msg)
        sender ! BMessage(s"(乔峰):挺猛，看我降龙十八掌...第 $count 掌")
      }

    }
    case StartMessage(msg)=>{
      println(s"BActor $msg")
      a ! StartMessage("黄飞鸿；在下黄飞鸿！看招！！")
    }
  }
}

object ActorDemo {
  def main(args: Array[String]): Unit = {
    val system = ActorSystem("ABsystem")
    val a = system.actorOf(Props[AActor],"A")
    val b = system.actorOf(Props[new BActor(a)],"B")
    b!StartMessage("乔峰：在下乔峰！请赐教！！")


  }
}
